<template>
    <div class="workspace">
        <div class="toolbar">
            <el-tooltip class="item" effect="dark" content="放大" placement="right">
                <div class="toolbar-item" @click="zoomIn" v-if="mapTools.zoomIn==true"><i
                        class="iconfont icon-plus"></i></div>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="缩小" placement="right">
                <div class="toolbar-item" @click="zoomOut" v-if="mapTools.zoomOut==true"><i
                        class="iconfont icon-minus"></i></div>
            </el-tooltip>
            <!--            <el-tooltip class="item" effect="dark" content="图层管理" placement="right">-->
            <!-- <div class="toolbar-item" v-if="mapTools.layerManager==true">
                <i class="iconfont icon-clone"></i>
                <div class="toolbar-item-open">
                    <template v-if="thematicLegendItemShowFlag">
                        <el-checkbox @change="toggleMapLayers(thematicLegendItem)" v-model="thematicLegendItem.visible"
                                     :label="thematicLegendItem.label"></el-checkbox>
                    </template>
                    <template v-for="(item, index) in legendData[1].items">
                        <el-checkbox @change="toggleMapLayers(item)" v-model="item.visible" :label="item.label"
                                     :key="index"></el-checkbox>
                    </template>
                </div>
            </div> -->
            <!--            </el-tooltip>-->
            <el-tooltip class="item" effect="dark" content="全幅显示" placement="right">
                <div class="toolbar-item" @click="fullExtent" v-if="mapTools.fullExtent==true"><i
                        class="iconfont icon-arrows-alt"></i></div>
            </el-tooltip>
            <el-tooltip class="item"  effect="dark" placement="right" disabled> <!--//"#13ce66"  -- active-color= "#1E90FF" inactive-color="#ff4949" -->
              <div class="toolbar-item" @click.self="layerSwitchPane" v-if="mapTools.baseMapManager==true">
                <i class="iconfont icon-map" @click.self="layerSwitchPane"></i>
                <!-- <div class="toolbar-item-open"> -->
                <div class="toolbar-item-pane" v-show="isSwitchLayer">
                  <div class="layer-type" style="text-align:left;padding-left:5px;margin-top:67px;">
                      <!-- {{layerSwitch==true ? "电子地图":"遥感影像" }} inactive-color="#ff4949     inactive-color="#13ce66"" -->
                      <el-switch
                      v-model="layerSwitch"
                      inactive-color="#1E90FF"
                      active-text="遥感影像"
                      inactive-text="电子地图">
                    </el-switch>
                  </div>
                </div>
              </div>

            </el-tooltip>
            <el-tooltip class="item"  effect="dark" placement="right" disabled> <!--//"#13ce66"  -- active-color= "#1E90FF" inactive-color="#ff4949" -->
              <div class="toolbar-item" @click.self="showLayerPane" v-if="mapTools.layerManager==true">
                <i class="iconfont icon-map" @click.self="showLayerPane"></i>
                <!-- <div class="toolbar-item-open"> -->
                <div class="toolbar-item-pane" v-show="layerPaneVisible">
                  <div class="layer-state" style="text-align:left;padding-left:5px;">
                      {{layerState==true ? "显示图层":"隐藏图层" }}
                      <el-switch
                      v-model="layerState"
                      inactive-text-color="#fff">
                    </el-switch>
                  </div>
                  <div class="layer-opacity">
                    <span class="demonstration" style="margin-left:-121px">图层透明度</span>
                    <el-slider
                        v-model="layerOpacity"
                        :step="0.1"
                        :max="1"
                        show-stops>
                    </el-slider>
                  </div>
                </div>
              </div>

            </el-tooltip>

            <!-- <el-tooltip class="item" effect="dark" content="搜索" placement="right">
                <div class="toolbar-item" v-if="mapTools.search==true"><i class="iconfont icon-search"></i></div>
            </el-tooltip> -->
            <!-- <el-tooltip class="item" effect="dark" content="分屏" placement="right">
                <div class="toolbar-item" @click="handleClickSplitMap" v-if="mapTools.splitMap==true"><i
                        class="iconfont icon-Split"></i></div>
            </el-tooltip> -->
        </div>
        <div :id="mapContainerId" class="map-container" style="cursor:pointer"></div>
        <MapLegend :legendData="legendData"></MapLegend>
        <!-- <div class="overlay-show" v-if="mapTools.isOverlayShow">
            <el-select
                    placeholder="切换地图"
                    v-model="overlayDefault"
                    @change="overlayChangeHandle">
                <el-option
                        v-for="item in overlayList"
                        :key="item"
                        :label="item"
                        :value="item"
                ></el-option>
            </el-select>
        </div> -->
    </div>

</template>
<script>
import { loadEsriModule } from '@/utils/jsapi'
import env from '@/utils/env'
import MapLegend from './MapLegend'
import MapUtils from '@/utils/MapUtils'
import { synchronizeViews } from '@/utils/synchronizeView'
import Axios from 'axios'
import bus from '@/modules/eventbus'
import regionCenters from '@/utils/regionCenters'
import createFlyLayer from '@/utils/createFlyLayer'
// import { chaiweiPopupTemplate } from '@/utils/layerPopupTemplate'
import ygyx_bg from '../assets/images/ygyx.png'
const EVENT_SPLIT_MAP = 'splitMapEvent'
const EVENT_MAP_POPUP = 'showMapPopupEvent'

export default {
  name: 'ArcMap',
  components: {
    MapLegend
  },
  props: {
    spatialUnit: {
      type: String,
      default () {
        return '0'
      }
    },
    mapType: {
      type: String,
      default () {
        return 'vector'
      }
    },
    mapID: {
      type: String,
      default () {
        return 'vector'
      }
    },
    mapTools: {
      type: Object,
      default () {
        return {
          zoomIn: true,
          zoomOut: true,
          layerManager: true,
          baseMapManager: false,
          layerOpacity: false,
          fullExtent: true,
          search: true,
          splitMap: true,
          isOverlayShow: false,
          isFloatTestFlag: false
        }
      }
    },
    isSplit: {
      type: Boolean,
      default () {
        return false
      }
    },
    renderData: {
      type: Object,
      default () {
        return {
          'regionNums': [],
          'classBreaks': [],
          'isRender': false,
          'featureLayerCreateFlag': 'source',
          'featureLayerUrl': '',
          'renderLabel': '',
          'isUniqueRenderWhenUrl': false
        }
      }
    }
  },
  data () {
    return {
      defaultCenter: env.getInitialExtent().center,
      defaultScale: env.getInitialExtent().scale,
      minScale: env.getInitialExtent().minScale,
      maxScale: env.getInitialExtent().maxScale,
      defaultExtent: env.getInitialExtent().extent,
      bakExtent: env.getInitialExtent().extent2,
      defaultSpatialReference: env.getInitialExtent().wkt,
      codeField: env.getRegionFields().codeField,
      nameField: env.getRegionFields().nameField,
      xzCodeField: env.getRegionFields().xzCodeField,
      qxCodeField: env.getRegionFields().qxCodeField,
      identifyLayerIds: env.getIdentifyLayerIds(),
      mapContainerId: `map-${parseInt(Math.random() * 1000)}`,
      mapView: null,
      map: null,
      mapViewLoaded: false,
      mapData: {},
      regionPopupTemplate: env.getRegionPopup(),
      thematicLegendItem: { id: 'layer-g', label: '专题图层', alias: '专题图层', color: '#E1E1E1', visible: true },
      thematicLegendItemShowFlag: false,
      legendData: this.mapID == 'vector' ? [{
        title: '图例',
        visible: false,
        items: [{ id: 0, label: '当月实施量', alias: '当月实施量', color: this.curColor, border: 'none', visible: true, isRound: true }]
      }] : [
        {
          title: '遥感影像',
          visible: true,
          items: [{ id: 0, label: this.curYear + '年' + this.curMonth + '月', alias: this.curYear + '年' + this.curMonth + '月', color: 'url(' + ygyx_bg + ') center center no-repeat', border: 'none', visible: true }]
        },
        {
          title: '行政边界',
          visible: true,
          items: [{ id: 0, label: '村界', alias: '村界', color: 'none', border: '2px solid #E1E1E1', visible: true }]
        },
        {
          title: '拆违图斑',
          visible: true,
          items: [
            { id: 0, label: this.curYear + '年', alias: this.curYear + '年', color: 'none', border: '2px solid #FF0000', visible: true },
            { id: 1, label: '选中图斑', alias: '选中图斑', color: 'none', border: '2px solid #7FFF00', visible: true }
          ]
        }
      ],
      legendDataDict: {
        'anualwj': { 0: [{ id: 0, label: '实施量', alias: '实施量', color: '#FF0000', border: 'none', visible: false, isRound: true }] },
        'ttyd': {
        //  0: [{ id: 0, label: '任务量', alias: '任务量', color: this.curColor, visible: true, isRound: true }],
          0: [{ id: 0, label: '当月实施量', alias: '当月实施量', color: this.curColor, border: 'none', visible: true, isRound: true }],
          1: [{ id: 0, label: '实施进度', alias: '实施进度', color: this.curColor, border: 'none', visible: true, isRound: true }]
        },
        'wjcc': {
          //   0: [{ id: 0, label: '任务量', alias: '任务量', color: this.curColor, visible: true, isRound: true }],
          0: [{ id: 0, label: '当月实施量', alias: '当月实施量', color: this.curColor, border: 'none', visible: true, isRound: true }],
          1: [{ id: 0, label: '实施进度', alias: '实施进度', color: this.curColor, border: 'none', visible: true, isRound: true }]
        },
        'rksj': {
          0: [{ id: 0, label: '拆违疏解居住人口变化', alias: '拆违疏解居住人口变化', color: this.curColor, border: 'none', visible: true, isRound: true }],
          1: [{ id: 0, label: '拆违疏解就业人口变化', alias: '拆违疏解就业人口变化', color: this.curColor, border: 'none', visible: true, isRound: true }],
          2: [{ id: 0, label: '行政区内居住人口数', alias: '行政区内居住人口数', color: this.curColor, border: 'none', visible: false, isRound: true }],
          3: [{ id: 0, label: '行政区内就业人口数', alias: '行政区内就业人口数', color: this.curColor, border: 'none', visible: false, isRound: true }]
        },
        'cytz': {
        //  0: [{ id: 0, label: '企业数量', alias: '企业数量', color: this.curColor, visible: true, isRound: true }],
          0: [{ id: 0, label: '拆违疏解企业数量变化', alias: '拆违疏解企业数量变化', color: this.curColor, border: 'none', visible: true, isRound: true }]

        },
        'spotsdetail': {
          0: [{ id: 0, label: this.curYear + '年全年拆违图斑', alias: this.curYear + '年全年拆违图斑', color: 'none', border: '2px solid #FF0000', visible: true }]
        }
      },
      isChangeSpatialUnit: false,
      overlayList: [],
      overlayDefault: '遥感影像',
      scaleDict: {
        1: 1000000,
        2: {
          '110101': 64000,
          '110102': 64000,
          '110105': 200000,
          '110106': 125000,
          '110107': 64000,
          '110108': 125000,
          '110109': 250000,
          '110111': 250000,
          '110112': 216000,
          '110113': 216000,
          '110114': 216000,
          '110115': 216000,
          '110116': 450000,
          '110117': 216000,
          '110118': 360000,
          '110119': 250000,
          '110228': 360000,
          '110229': 250000
        },
        3: 50000,
        4: 10000
      },
      odLayer: null,
      odChart: null,
      mapTempData: null,
      isODLayer: false,
      isBubbleLayer: true,
      coverlayerParam: null,
      subLayerId: null,
      layerState: false,
      layerSwitch: false,
      layerOpacity: 0.7,
      layerPaneVisible: false,
      isSwitchLayer: false,
      curShpLegend: null,
      curBaseMapType: 'dzdt',
      screenWidth: '',
      screenHeight: ''
    }
  },
  computed: {
    // 各级行政编码字段
    queryFieldDict () {
      return { 1: this.codeField, 2: this.codeField, 3: this.codeField, 4: 'czcode' }
    },
    // 地图参数
    paramsCondition () {
      return JSON.stringify(this.$store.getters.paramsCondition)
    },
    curfeature (val) {
      return this.$store.getters.curfeature
    },
    curMapData () {
      return this.$store.getters.curmapdata
    },
    // 空间选择名称（地图下钻同步）
    curregionobj: {
      set (val) {
        this.$store.state.regionobj = val
      },
      get () {
        return this.$store.getters.curregionobj
      }
    },
    curLeftMapServerUrl () {
      return this.$store.getters.curLeftMapServerUrl
    },
    curRightMapServerUrl () {
      return this.$store.getters.curRightMapServerUrl
    },
    curColor () {
      if (this.$store.getters.curColor) { return this.$store.getters.curColor[0] }
    },
    curYear () {
      return this.$store.getters.curyear
    },
    curMonth () {
      return this.$store.getters.curmonth
    },
    curRegionCode () {
      return this.$store.getters.curRegionCode
    },
    curRegionName () {
      return this.$store.getters.curRegionName
    },
    curRegionLevel () {
      return this.$store.getters.curRegionLevel
    },
    isVisibleRightMap () {
      return this.$store.getters.isVisibleRightMap
    }
  },
  watch: {
    curMonth (newVal) {
      let regionLevel = parseInt(this.$store.getters.curRegionLevel)
      this.legendData[0].visible = regionLevel == 3
      if (regionLevel == 3) {
        let month = newVal
        this.legendData[0].items[0].label = month != '13' ? this.curYear + '年' + month + '月' + '拆违图斑' : this.curYear + '年全年拆违图斑'
        this.legendData[0].items[0].alias = month != '13' ? this.curYear + '年' + month + '月' + '拆违图斑' : this.curYear + '年全年拆违图斑'
      }
    },
    // 切换底图
    layerSwitch (val) {
      this.curBaseMapType = val ? 'ygyx' : 'dzdt'
      let url = env.getDefaultBaseMap()[this.curBaseMapType]
      MapUtils.addBaseLayer(this.mapView, url, this.curRegionLevel)
      let layer_region = this.mapView.map.layers.find(lyr => {
        return lyr.id === 'layer-region'
      })
      let layer_cun = layer_region.findSublayerById(4)
      layer_cun.labelsVisible = val
    },
    // 图斑详情页专题图层控制开/关
    layerState (val) {
      this.toggleMapLayers(val)
    },
    // 图斑详情页专题图层透明度动态设置
    layerOpacity (val) {
      let fLayer = this.map.layers.find(lyr => {
        return lyr.id === 'layer-shp'
      })
      if (fLayer) {
        fLayer.opacity = val
      }
    },
    isVisibleRightMap (val) {
      if (val) {
        this.splitMap()
      }
    },
    $route: {
      handler (val) {
        if (val.path.startsWith('/monitoringindex')) this.isBubbleLayer = false
      }
    },
    // 监听地图数据变化，更新气泡图
    curMapData (mapdata) {
      if (this.mapID == 'vector') {
        this.mapTempData = mapdata
        let regionLevel = parseInt(this.$store.getters.curRegionLevel)
        if (this.mapView && mapdata) {
          // 清除地图上可能存在的气泡图层或专题图层
          MapUtils.removeLayerByLayerIds(this.mapView, 'layer-bubble')
          MapUtils.removeLayerByLayerIds(this.mapView, 'layer-shp')
          MapUtils.removeLayerByLayerIds(this.mapView, 'layer-img')
          MapUtils.removeLayerByLayerIds(this.mapView, 'layer-boundary')
          if (mapdata.length > 0) {
            if (mapdata[0].regioncode) this.mapView.graphics.removeAll()// 清除上一次点击目标
            // 若mapdata中不包含飞线相应关键字信息，则画气泡图，否则画飞线图
            if (!mapdata[0]['fromName']) {
              // 清掉od图层
              this.removeODLayer()
              // 重新初始化MapView
              if (this.odLayer) {
                this.initMapView(false)
              }
              if (regionLevel < 3) {
                this.switchLegend(this.$route.path, this.$store.getters.curindex)
                MapUtils.removeLayerByLayerIds(this.mapView, 'layer-bubble')
                var graphicsLayer = MapUtils.createGraphicsLayer(this.mapView, regionLevel, this.$store.getters.curRegionCode, mapdata, this.curColor)
              }
            } else {
              this.legendData[0].visible = false
              this.createODLayer(mapdata)
            }
          } else {
            this.mapView.popup.clear()
            this.mapView.popup.close()
            this.reInitMapView()
          }
        }
      }
    },
    curLeftMapServerUrl (newUrl, oldUrl) {
      if (this.mapID == 'vector1') {
        this.overlayChangeHandle(newUrl)
      }
    },
    curRightMapServerUrl (newUrl, oldUrl) {
      if (this.mapID == 'vector2') {
        this.overlayChangeHandle(newUrl)
      }
    }
  },
  created () {
  },
  methods: {
    // 格式化乡镇图层where语句
    xzLayerExpression (queryField, regionCode, whereSql) {
      if (regionCode && regionCode.includes('110106') && whereSql) {
        let exceptCodeList = ['110106100', '110106019', '110106017']
        whereSql += ' and ('
        for (let i = 0; i < exceptCodeList.length - 1; i++) {
          whereSql += this.codeField + " <> '" + exceptCodeList[i] + "') and ("
        }
        whereSql += this.codeField + " <> '" + exceptCodeList[exceptCodeList.length - 1] + "')"
      }
      return whereSql
    },
    // 图层切换按钮
    layerSwitchPane () {
      this.isSwitchLayer = !this.isSwitchLayer
    },
    // 图层面板开关
    showLayerPane () {
      this.layerPaneVisible = !this.layerPaneVisible
    },
    // 高亮当前所选图斑
    highlightFeature (view, feature) {
      view.graphics.removeAll()
      let graphic = feature
      graphic.symbol = {
        type: 'simple-fill',
        color: [127, 255, 0, 0],
        outline: {
          type: 'simple-line',
          color: [127, 255, 0, 1], // [176, 255, 255, 1],
          width: 2,
          style: 'solid'
        }
      }
      view.graphics.add(graphic)// 添加新的点击目标
    },
    // 图斑详情页左右地图联动
    async splitMap () {
      const [watchUtils] = await loadEsriModule(['esri/core/watchUtils'])
      let mainView = this.$store.getters.leftMapView
      let splitView = this.$store.getters.rightMapView
      synchronizeViews([mainView, splitView], watchUtils)
    },

    // 图斑详情页添加图层
    overlayChangeHandle (param) {
      // console.log(param)
      if (param.length > 0) {
        this.coverlayerParam = param
        let val = param[0]
        let self = this
        let url = val['server_url']
        let layerType = val['layer_type']
        let legendItem = eval('(' + val['legend'] + ')')
        let popup = val['popup']
        // if (val['popup']) {
        //   popup = val['popup'].replace('NumFormat', 'NumberFormat(places:2)')
        // }
        let popupTemplate = popup ? eval('(' + popup + ')') : null
        this.mapView.popup.close()

        let labelName = this.mapID == 'vector1' ? this.$store.getters.curLeftTabVal : this.$store.getters.curRightTabVal
        // 为遥感影像图例色块添加样式
        if (layerType == 'img') {
          for (let i = 0; i < legendItem['items'].length; i++) {
            legendItem['items'][i].border = 'none'
            legendItem['items'][i].color = 'url(' + ygyx_bg + ') center center no-repeat'
          }
        }
        let legendDict = { 'img': 0, 'boundary': 1, 'shp': 3 }
        MapUtils.addLayer(this.mapView, url, layerType, this.layerOpacity, labelName, popupTemplate, function (layer, subLayerId) {
          let fLayer = self.mapView.map.layers.find(lyr => {
            return lyr.id === 'layer-chaiwei'
          })
          self.mapView.map.reorder(fLayer, self.mapView.map.layers.length - 1)
          // 设置当前图层显示
          if (layerType == 'shp') {
            self.layerState = true
          }
          if (layer.type !== 'tile') {
            // 更新当前图层的索引
            self.subLayerId = layerType == 'shp' ? subLayerId : self.subLayerId

            layer.when(function (layerView) {
              if ((typeof subLayerId) !== 'undefined') {
                let subLayers = layer.allSublayers.items
                for (let i = 0; i < subLayers.length; i++) {
                  let subLayer = subLayers[i]
                  if (subLayer.id == subLayerId) {
                    subLayer.visible = true
                  } else {
                    subLayer.visible = false
                  }
                }
              }
            })
          }

          let legendIndex = legendDict[layerType]
          // // 2、更改地图及图例
          // let legendItem = eval('(' + val['legend'] + ')')
          legendItem.items[0].visible = true
          self.legendData.splice(legendIndex, 1, {
            title: legendItem.title,
            items: legendItem.items,
            visible: true
          })

          // 3、更改
          self.thematicLegendItemShowFlag = true
        })
      }
    },
    createODLayer (mapData) {
      if (this.mapID == 'vector') {
        this.isODLayer = true
        this.isBubbleLayer = true
        this.odLayer = createFlyLayer(this.mapView, mapData, this.odChart)
        let regionCode = this.$store.getters.curRegionCode
        let regionName = this.$store.getters.curRegionName
        let self = this
        if (this.$store.getters.isMapClick) {
          this.$store.dispatch('changeIsMapClick', false)
        }
        if (!this.odChart) {
          this.odLayer.then(function (result) {
            self.odChart = result
            self.$emit('odChart', result)
          //    bus.$emit('drillDownName',{regioncode: regionCode,regionname: regionName})
          })
        } else {
          this.odLayer = this.odChart
          self.$emit('odChart', this.odChart)
        }
      }
    },
    removeODLayer () {
      if (this.odChart) {
        // 仅当从飞线图切换到气泡图时进入
        this.odChart.remove()
        this.odChart = null
        let layer_region = this.mapView.map.layers.find(lyr => {
          return lyr.id === 'layer-region'
        })
        let layer_qx = layer_region.findSublayerById(1)
        layer_qx.popupEnabled = true
      }
    },
    reInitMapView () {
      // if (this.mapID == 'vector') {
      //   if (!this.isBubbleLayer) {
      //     if (this.$store.getters.curRegionLevel == 1) {
      //       this.initMapView()
      //       this.isBubbleLayer = true
      //       this.odChart = null
      //     }
      //   } else if (this.isODLayer) {
      //     this.initMapView()
      //     this.odChart = null
      //   }
      // }
    },
    switchODCenter () {
      if (this.odLayer) {
        var self = this
        this.odLayer.then(function (result) {
          let myChart = result
          let option = myChart.getChartOption()
          option.legend.selected = {}
          option.legend.data.forEach(function (value) {
            option.legend.selected[value] = false
          })
          let regionName = self.$store.getters.curRegionName
          option.legend.selected[regionName] = true
          option.legend.selectedMode = 'single'
          option.legend.visible = true
          myChart.setChartOption(option)
        })
      }
    },
    switchLegend (path, curIndex) {
      let pathList = path.split('/')
      let pathTail = pathList[pathList.length - 1]
      this.legendData[0].visible = this.mapTempData ? this.mapTempData.length > 0 : false
      this.legendData[0].items = this.legendDataDict[pathTail][curIndex]
      this.legendData[0].items[0].color = this.curColor ? this.curColor : this.legendData[0].items[0].color
      if (pathTail.includes('ttyd') || pathTail.includes('wjcc')) {
        this.legendData[0].items[0].label = this.curMonth == '13' ? '全年实施量' : '当月实施量'
        this.legendData[0].items[0].alias = this.curMonth == '13' ? '全年实施量' : '当月实施量'
      }
    },
    zoomIn () {
      let view = this.odChart ? this.odChart.getMapView() : this.mapView
      view.when(function () {
        let scale = view.scale - (view.scale * 0.5)
        let zoom = view.zoom
        //  console.log(view.zoom,scale)
        if (zoom < 0) {
          view.goTo({
            center: view.center,
            scale: scale
          })
        } else {
          view.goTo({
            center: view.center,
            zoom: view.zoom + 1
          })
        }
      })
    },
    zoomOut () {
      let view = this.odChart ? this.odChart.getMapView() : this.mapView
      view.goTo({
        center: view.center,
        scale: view.scale + (view.scale * 0.5)
      }, {
        animate: true,
        duration: 1000
      })
    },
    fullExtent () {
      let view = this.odChart ? this.odChart.getMapView() : this.mapView
      view.goTo({
        target: this.odChart ? view.center : this.defaultCenter,
        scale: this.odChart ? 1260000 : this.defaultScale
      }, {
        animate: true,
        duration: 1000
      })
      // this.mapView.goTo({
      //   target: this.defaultCenter,
      //   scale: this.defaultScale
      // }, {
      //   animate: true,
      //   duration: 1000
      // })
    },
    toggleMapLayers (isOpen) {
      if (this.coverlayerParam) {
        let val = this.coverlayerParam[0]
        this.mapView.popup.close()
        const fLayer = this.map.layers.find(lyr => {
          return lyr.id === 'layer-shp'
        })
        if (fLayer) {
          if (fLayer.type == 'tile') {
            fLayer.visible = isOpen
          } else {
            let subLayers = fLayer.allSublayers.items
            let subLayerIndex = this.subLayerId ? this.subLayerId : 0
            let layer = subLayers[subLayerIndex]
            let isVisible = layer.visible
            layer.visible = !isVisible
          }
          // 更新专题图层图例的可见性
          if (isOpen) {
            let layerType = val['layer_type']
            let legendItem = eval('(' + val['legend'] + ')')
            legendItem.items[0].visible = true
            if (layerType == 'shp') {
              this.legendData.splice(3, 1, {
                title: legendItem.title,
                items: legendItem.items,
                visible: true
              })
            } else {
              this.legendData.splice(3, 1, this.curShpLegend)
            }
          } else {
            this.curShpLegend = this.legendData[3]
            this.legendData.splice(3, 1)
          }
        }
      }
    },
    handleClickSplitMap () {
      this.$emit(EVENT_SPLIT_MAP)
    },
    async showMapPopup (regionCode, mapPoint) {
      let popup = this.mapView.popup
      popup.location = mapPoint
      // 根据regionCode查找feature
      let result = await MapUtils.queryFeatures(this.mapView, regionCode)
      popup.features = result.features
      popup.visible = true
    },
    zoomToRegion (mapPoint) {
      if (this.mapViewLoaded) {
        this.mapView.goTo({
          target: mapPoint,
          scale: 14
        }, {
          animate: true,
          duration: 1000
        })
      }
    },
    getMapView () {
      return this.mapView
    },
    getMapViewLoaded () {
      return this.mapViewLoaded
    },

    switchTBView () {
      var self = this
      let regionName = this.$store.getters.curRegionName
      let year = this.$store.getters.curyear

      this.mapView.when(function () {
        let feature = self.$store.getters.curfeature[0]
        // console.log(feature)
        // 进入图斑页后
        // self.legendData.splice(3,1)
        // MapUtils.removeLayerByLayerIds(self.mapView, 'layer-shp')
        // MapUtils.removeLayerByLayerIds(self.mapView, 'layer-boundary')
        self.legendData[2].items[0].label = year + '年'
        self.legendData[2].items[0].alias = year + '年'
        let layer_region = self.mapView.map.layers.find(lyr => {
          return lyr.id === 'layer-region'
        })

        var layer_xz = layer_region.findSublayerById(0)
        var layer_qx = layer_region.findSublayerById(1)
        var layer_xz2 = layer_region.findSublayerById(2)
        let layer_cun = layer_region.findSublayerById(4)
        layer_xz.visible = false
        layer_qx.visible = false
        layer_cun.visible = false
        layer_xz.popupEnabled = false

        // self.mapView.goTo({
        //   center: feature.geometry.centroid,
        //   scale: 1000
        // })
        self.mapView.goTo(feature.geometry.extent)
        self.mapView.graphics.removeAll()// 清除上一次点击目标
        self.mapView.popup.visible = false
        MapUtils.removeLayerByLayerIds(self.mapView, 'layer-bubble')

        let layer_chaiwei = self.mapView.map.layers.find(lyr => {
          return lyr.id === 'layer-chaiwei'
        })

        if (layer_chaiwei) {
          let layer_chaiwei_0 = layer_chaiwei.findSublayerById(0)
          layer_chaiwei_0.visible = true
          layer_chaiwei_0.popupEnabled = false
          layer_chaiwei_0.opacity = 0.8
        }

        if (feature.attributes) {
          let attributes = feature.attributes
          let baseInfodata = MapUtils.displayFieldsInfo(self.curYear, attributes)
          bus.$emit('getspotsbaseinfo', baseInfodata)
        }
        self.highlightFeature(self.mapView, feature)
      })
    },
    mapSwitch (mapData) {
      this.mapView.graphics.removeAll()// 清除上一次点击目标
      this.mapView.popup.visible = false
      let regionCode = mapData['regioncode']
      let regionName = mapData['regionname']
      let regionLevel = mapData['regionlevel']
      let feature = mapData['feature'] ? mapData['feature'] : this.$store.getters.curfeature
      let center = mapData['center']
      let renderData = mapData['renderData']
      let year = this.$store.getters.curyear
      let month = this.$store.getters.curmonth
      // 更新密云和延庆的行政代码
      regionCode = MapUtils.modifyErrorCode(regionCode, 'toLayer')
      let layer_region = this.mapView.map.layers.find(lyr => {
        return lyr.id === 'layer-region'
      })
      let layer_chaiwei = this.mapView.map.layers.find(lyr => {
        return lyr.id === 'layer-chaiwei'
      })
      let layer_chaiwei_0 = layer_chaiwei.findSublayerById(0)

      let queryField = this.queryFieldDict[regionLevel]
      let scale = regionLevel == 2 ? this.scaleDict[regionLevel][regionCode] : this.scaleDict[regionLevel]
      // 如果isSplit为false，当前界面为主界面,为true,说明已跳到了图斑详情页
      if (!this.isSplit) {
        this.map.allLayers.items[0].visible = true
        // regionLevel小于4，regionLevel=1-->北京区县层;regionLevel=2-->某个区县的乡镇层;regionLevel=3-->某个乡镇的村界层与拆违图斑层
        // regonLevel大于等于4，则跳到图斑详情页
        if (regionLevel < 4) {
          let layer_xz = layer_region.findSublayerById(0)
          let layer_qx = layer_region.findSublayerById(1)
          let layer_xz2 = layer_region.findSublayerById(2)
          let layer_cun = layer_region.findSublayerById(4)
          if (regionLevel == 1) {
            layer_qx.definitionExpression = '1=1'
            layer_qx.labelsVisible = false
            layer_qx.popupEnabled = true
            layer_xz.popupEnabled = false
            layer_qx.renderer = null

            layer_qx.visible = true
            layer_xz.visible = false
            layer_xz2.visible = false
            layer_cun.visible = false
            layer_qx.renderer = {
              type: 'simple',
              symbol: {
                type: 'simple-fill',
                color: [0, 0, 0, 0],
                outline: {
                  width: 1,
                  color: [255, 255, 255, 1]
                }
              }
            }
            this.map.allLayers.items[0].visible = false
          } else if (regionLevel == 2) {
            let whereSql = queryField + " like '%" + regionCode + "%'"
            layer_xz.definitionExpression = this.xzLayerExpression(queryField, regionCode, whereSql)
            layer_qx.definitionExpression = this.codeField + " <> '" + regionCode + "'"
            layer_qx.visible = true
            layer_xz.visible = true
            layer_qx.popupEnabled = false
            layer_xz.popupEnabled = true
            layer_qx.labelsVisible = true
            layer_xz2.visible = false
            // layer_xz.labelsVisible = false
            layer_xz2.labelsVisible = false
            layer_cun.visible = false
            layer_qx.renderer = {
              type: 'simple',
              symbol: {
                type: 'simple-fill',
                color: [0, 0, 0, 0.7],
                outline: {
                  width: 1,
                  color: [190, 190, 190, 0.5]
                }
              }
            }
            layer_xz.renderer = {
              type: 'simple',
              symbol: {
                type: 'simple-fill',
                color: [0, 0, 0, 0.7],
                outline: {
                  width: 2,
                  color: '#fff'
                }
              }
            }
          } else if (regionLevel == 3) {
            // 花乡地区与新界街道通用
            if (regionCode.includes('110106018')) {
              regionCode = '110106010000'
            }
            let whereSql2 = this.codeField + " <> '" + regionCode.slice(0, 9) + "'"
            layer_cun.definitionExpression = this.xzCodeField + " = '" + regionCode.slice(0, 9) + "'"
            layer_xz.definitionExpression = this.codeField + " = '" + regionCode.slice(0, 9) + "'"
            layer_xz2.definitionExpression = this.xzLayerExpression(this.codeField, regionCode, whereSql2)// and qxcode = '"+regionCode.slice(0,6)+"'"
            layer_qx.visible = false
            layer_xz2.visible = true
            //  layer_xz2.labelsVisible = true
            layer_qx.popupEnabled = false
            layer_xz.popupEnabled = false
            layer_cun.visible = true
            layer_cun.labelsVisible = this.curBaseMapType == 'ygyx'

            layer_xz.renderer = {
              type: 'simple',
              symbol: {
                type: 'simple-fill',
                color: [0, 0, 0, 0],
                outline: {
                  width: 2,
                  color: '#fff'
                }
              }
            }
            layer_xz2.renderer = {
              type: 'simple',
              symbol: {
                type: 'simple-fill',
                color: [0, 0, 0, 0.7], // [19, 41, 55, 0],
                outline: {
                  width: 2,
                  color: [190, 190, 190, 0.5]// '#0692a4',//"white",
                }
              }
            }
          }
          if (layer_chaiwei) {
            if (regionLevel == 3) {
              // 通过日期来筛选当前显示图斑量
              layer_chaiwei_0.definitionExpression = MapUtils.getTimeFilter(year, month)
              layer_chaiwei_0.visible = true
            } else {
              layer_chaiwei_0.visible = false
            }
          }
          // 如果是东西城区，放大比例尺单独扩大
          if (regionLevel == 3 && (regionCode.slice(0, 6).includes('110101') || regionCode.slice(0, 6).includes('110102'))) {
            scale = 16000
            // console.log(scale)
          }
          this.mapView.goTo({
            target: regionLevel == 1 ? center : feature,
            scale: scale
          }, {
            // animate: true,
            // duration: 1000
          })

          if (!this.odLayer) MapUtils.removeLayerByLayerIds(this.mapView, 'layer-bubble')
        } else {
          this.$router.push('/spotsdetail')
          if (this.mapView.popup.visible) {
            this.mapView.popup.close()
            this.mapView.popup.clear()
          }
        }
      } else {
        if (this.mapID !== 'vector') {
          if (parseInt(regionLevel) > 3) {
            this.switchTBView()
          }
        }
      }
    },

    async initMapView (isOffSet) {
      const [esriConfig, Map, Basemap, MapImageLayer, MapView, FeatureLayer, SpatialReference, Graphic, Point, Extent, IdentifyTask, IdentifyParameters, TileLayer, urlUtils] =
                    await loadEsriModule(['esri/config', 'esri/Map', 'esri/Basemap',
                      'esri/layers/MapImageLayer', 'esri/views/MapView', 'esri/layers/FeatureLayer', 'esri/geometry/SpatialReference',
                      'esri/Graphic', 'esri/geometry/Point', 'esri/geometry/Extent', 'esri/tasks/IdentifyTask',
                      'esri/tasks/support/IdentifyParameters', 'esri/layers/TileLayer', 'esri/core/urlUtils'])
      esriConfig.fontsUrl = window.appcfg.agsFonts
      let proxyUrl = window.appcfg.proxyUrl
      window.appcfg.urlPrefix.forEach(url => {
        urlUtils.addProxyRule({
          urlPrefix: url,
          proxyUrl: proxyUrl
        })
      })

      let myBaseMap = new Basemap({
        baseLayers: [new TileLayer({
          url: env.getDefaultBaseMap()[this.curBaseMapType],
          visible: true
        })],
        title: 'Custom Basemap'
      })

      if (this.mapType == 'vector') {
        this.map = new Map({
          // basemap: myBaseMap,
          layers: [
            new TileLayer({
              url: env.getDefaultBaseMap()[this.curBaseMapType],
              id: 'layer-basemap',
              visible: false
            }),
            new MapImageLayer({
              url: env.getDefaultVectorMap(),
              id: 'layer-region',
              sublayers: env.getVectorSubLayers()
            })]
        })
      } else {
        this.map = new Map({
          basemap: myBaseMap,
          layers: [new MapImageLayer({
            url: env.getDefaultRasterMap()
          })]
        })
      }
      this.mapView = new MapView({
        container: this.mapContainerId,
        map: this.map,
        scale: this.defaultScale,
        id: this.mapID,
        extent: isOffSet ? new Extent({
          xmax: this.bakExtent.xmax,
          xmin: this.bakExtent.xmin,
          ymax: this.bakExtent.ymax,
          ymin: this.bakExtent.ymin,
          spatialReference: new SpatialReference({ wkt: env.getInitialExtent().wkt })
        }) : new Extent({
          xmax: this.defaultExtent.xmax,
          xmin: this.defaultExtent.xmin,
          ymax: this.defaultExtent.ymax,
          ymin: this.defaultExtent.ymin,
          spatialReference: new SpatialReference({ wkt: env.getInitialExtent().wkt })
        }),
        constraints: {
          rotationEnabled: false,
          minScale: this.minScale,
          maxScale: this.maxScale
        },
        popup: {
          highlightEnabled: true,
          dockEnabled: false,
          dockOptions: {
            breakpoint: false,
            position: 'top-right'
          }
        },
        ui: {
          components: []
        }
      })
      var layer_chaiwei = new MapImageLayer({
        id: 'layer-chaiwei',
        url: env.getOtherMapServer().chaiwei[this.curYear.toString()],
        sublayers: [ {
          id: 0,
          title: '拆违图斑',
          visible: false,
          source: {
            mapLayerId: 0
          },
          labelsVisible: false,
          popupTemplate: env.getChaiWeiPopup()[this.curYear.toString()],
          outFields: ['*'],
          renderer: {
            type: 'simple',
            symbol: {
              type: 'simple-fill',
              // style: 'none',
              color: [255, 0, 0, 0],
              outline: {
                type: 'simple-line',
                color: [255, 0, 0, 1],
                width: 2,
                style: 'solid'
              }
            }
          }
        }
        ]
      })
      this.mapView.map.add(layer_chaiwei)
      // 如果是图斑详情页，左侧地图或右侧地图返回左右view
      if (this.mapID == 'vector1') {
        this.$store.dispatch('changeLeftMapView', this.mapView)
      } else if (this.mapID == 'vector2') {
        this.$store.dispatch('changeRightMapView', this.mapView)
      }
      let self = this
      // 是否是进入图斑页 ，如果isSplit为true则进入图斑页，否则进入主界面
      if (this.isSplit) {
        this.mapSwitch(self.$store.getters.paramsCondition)
        this.initMapViewClick()
      } else {
        this.mapView.when(function () {
          self.defaultCenter = self.mapView.center
          self.mapViewLoaded = true
          self.$emit('loadState', true)
          self.switchLegend(self.$route.path, self.$store.getters.curindex)
          let curRegionLevel = self.$store.getters.curRegionLevel
          let curRegionCode = self.$store.getters.curRegionCode
          var graphicsLayer = MapUtils.createGraphicsLayer(self.mapView, curRegionLevel, curRegionCode, self.mapTempData, self.curColor)
          self.mapView.popup.on('trigger-action', function (event) {
            if (event.action.id === 'drill-btn') {
              let code = event.target.features[0].attributes[self.codeField]
              let name = event.target.features[0].attributes[self.nameField]
              let curRegionCode = code || self.$store.getters.curRegionCode
              // 更新密云和延庆区的行政编码
              curRegionCode = MapUtils.modifyErrorCode(curRegionCode, 'toGlobal')
              let curRegionLevel = parseInt(self.$store.getters.curRegionLevel)
              // 若当前下钻级别为最后一层时，不再自增
              curRegionLevel = curRegionLevel >= 4 ? curRegionLevel : curRegionLevel + 1
              let feature = event.target.features
              // console.log(feature)
              // 10.28，解决regioncode前端渲染列表判断问题，在前端修改regioncode
              name = name ? name.replace('区', '').replace('乡', '').replace('镇', '').replace('街道', '').replace('地区', '') : name
              bus.$emit('drillDownName', { regioncode: curRegionCode, regionname: name })
              self.$store.dispatch('changefeature', feature)
            }
          })
          self.mapView.watch('extent', function (event) {
            let curRegionCode = self.$store.getters.curRegionCode
            // console.log(self.mapView.zoom)
            // console.log(event)
            // console.log(curRegionCode + ':[' + event.center.x + ',' + event.center.y + '],' + self.mapView.scale)
          })
          let layer_region = self.mapView.map.layers.find(lyr => {
            return lyr.id === 'layer-region'
          })
          let layer_xz = layer_region.findSublayerById(0)
          let layer_xz2 = layer_region.findSublayerById(2)
          // 点击查询当前图层，判断是否是前的区县或新的乡镇，如果是新的区县则切换到该区县的乡镇图层，如果是新乡镇，则切换到该乡镇，
          // 否则只是弹出该乡镇的信息窗
          self.mapView.on('click', executeIdentifyTask)
          // 执行点击识别查询
          function executeIdentifyTask (event) {
            let regionlevel = self.$store.getters.curRegionLevel
            if (regionlevel >= 1 && regionlevel < 4) {
              var identifyTask, params
              identifyTask = new IdentifyTask(env.getDefaultVectorMap())

              params = new IdentifyParameters()
              params.tolerance = 3
              params.layerIds = self.identifyLayerIds
              params.layerOption = 'visible'
              params.width = self.mapView.width
              params.height = self.mapView.height
              params.returnGeometry = true
              params.geometry = event.mapPoint
              params.mapExtent = self.mapView.extent
              identifyTask
                .execute(params)
                .then(function (response) {
                  let curRegionCode = MapUtils.modifyErrorCode(self.$store.getters.curRegionCode, 'current')
                  let curRegionName = self.$store.getters.curRegionName
                  let curYear = self.$store.getters.curyear
                  let curMonth = self.$store.getters.curmonth

                  // 获得的features中第二层feature
                  var results = response.results[1]
                  // console.log(results)
                  // 查询获得的features中第一层feature的code值
                  let firstCode = response.results[0].feature.attributes[self.codeField]
                  // 查询获得的features中第二层feature的code、name值
                  let regionCode = results.feature.attributes[self.codeField]
                  let regionName = results.feature.attributes[self.nameField]

                  if (regionlevel < 3) {
                    // 判断查询结果的features中哪一个是
                    if (regionlevel == 1) {
                      results = response.results[0]
                      self.regionPopupTemplate.title = '<h4 style="color:yellow">{' + self.nameField + '}</h4>'.replace('yellow', self.curColor)
                    } else if (regionlevel == 2) {
                      // 因为查询结果中features中最上层为区县界，第二层为乡镇界，若点击区域为当前区县，则进行蒙板效果设置
                      if (firstCode.slice(0, 6) == curRegionCode.slice(0, 6)) {
                        results = response.results[1]
                        regionCode = results.feature.attributes[self.codeField]
                        layer_xz.definitionExpression = self.xzLayerExpression(self.codeField, regionCode, self.codeField + " LIKE '%" + regionCode.slice(0, 6) + "%' and " + self.codeField + " <> '" + regionCode + "'")
                        layer_xz2.definitionExpression = self.codeField + " = '" + regionCode + "'"
                        layer_xz2.visible = true
                        layer_xz2.labelsVisible = false
                        // 蒙板效果样式设置
                        layer_xz2.renderer = {
                          type: 'simple',
                          symbol: {
                            type: 'simple-fill',
                            color: [11, 17, 41, 0],
                            outline: {
                              width: 2,
                              color: '#fff'
                            }
                          }
                        }
                        self.regionPopupTemplate.title = '<h4 style="color:yellow">{' + self.qxCodeField + '}>{' + self.nameField + '}</h4>'.replace('yellow', self.curColor)
                      } else {
                        results = response.results[0]
                      }
                    }
                    results.feature.popupTemplate = self.regionPopupTemplate
                    regionCode = results.feature.attributes[self.codeField]
                    // 更新密云和延庆的行政代码
                    regionCode = MapUtils.modifyErrorCode(regionCode, 'toGlobal')
                    const { apiHost, apiPort } = window.appcfg.apiOption
                    let temp_path = self.$route.path.split('/')
                    let isSelectedPath = temp_path[2] == 'rksj' || temp_path[2] == 'cytz'
                    // 请求弹窗中要显示的信息
                    const url = `http://${apiHost}:${apiPort}/api/chaiweiserver?params={"year":"${curYear}","month":"${curMonth}","regioncode":"${regionCode}","path":"${temp_path[temp_path.length - 1]}"}`
                    Axios.get(url).then(res => {
                      // 如果请求到了数据则弹窗显示相应信息，否则弹窗显示暂无拆违数据
                      if (typeof res.data === 'object' || typeof res.data === 'number') {
                        let use = res.data[0] ? res.data[0]['areause'] : res.data
                        let build = res.data[0] ? res.data[0]['areabuild'] : null
                        results.feature.attributes['year'] = curYear
                        results.feature.attributes['month'] = curMonth == '13' ? '全年' : '截至' + curMonth + '月'
                        let flag = res.data[0] ? res.data.reduce(function getSum (total, num) {
                          return total + num
                        }) : res.data
                        if (flag == 0) {
                          results.feature.popupTemplate.content = '<ul><li>暂无拆违数据</li></ul>'
                        } else {
                          if (use && build) {
                            results.feature.attributes['area'] = use.toFixed(2).toString()
                            results.feature.attributes['renderval'] = build.toFixed(2).toString()
                          } else if (use && !build) {
                            results.feature.attributes['area'] = use.toFixed(2).toString()
                            results.feature.popupTemplate.content = results.feature.popupTemplate.content.replace('<li>累计违建拆除面积: {renderval}万平方米</li>', '')
                          } else if (!use && build) {
                            results.feature.attributes['renderval'] = build.toFixed(2).toString()
                            results.feature.popupTemplate.content = results.feature.popupTemplate.content.replace('<li>累计腾退用地面积: {area}公顷</li>', '')
                          } else {
                            results.feature.popupTemplate.content = '<ul><li>暂无拆违数据</li></ul>'
                          }
                        }
                        // 如果第一层feature的code小于等于当前code长度，并且两个code的前六位不相同，说明是在从一个区县切换到另一个区县
                        if ((firstCode.length <= curRegionCode.length) && (firstCode.slice(0, 6) != curRegionCode.slice(0, 6))) {
                          if (curRegionCode != '110000') {
                            self.mapView.popup.clear()
                          } else {
                            self.mapView.popup.open({
                              features: [results.feature]
                              // updateLocationEnabled: true
                            })
                          }
                        } else {
                          self.mapView.popup.open({
                            features: [results.feature]
                            // updateLocationEnabled: true
                          })
                        }
                      } else {
                        results.feature.popupTemplate.content = '<ul><li>暂无拆违数据</li></ul>'
                        self.mapView.popup.open({
                          features: [results.feature]
                          // updateLocationEnabled: true
                        })
                      }
                    })
                  } else {
                    firstCode = response.results[1].feature.attributes[self.codeField]
                    if ((firstCode.length == curRegionCode.length) && (firstCode != curRegionCode)) {
                      self.mapView.popup.clear()
                    }
                  }
                  // 获得最终的feature中的数据
                  regionCode = results.feature.attributes[self.codeField]
                  regionName = results.feature.attributes[self.nameField]
                  //  // 更新密云和延庆的行政代码
                  regionCode = MapUtils.modifyErrorCode(regionCode, 'toGlobal')
                  // 如果regionlevel大于1，并且当前行政代码长度大于等于点击选中的代码，两者也不相等，则向store更新code,name,feature
                  if (regionlevel > 1 && (curRegionCode.length >= regionCode.length) && (curRegionCode != regionCode)) {
                    regionName = regionName ? regionName.replace('区', '').replace('乡', '').replace('镇', '').replace('街道', '').replace('地区', '') : regionName
                    bus.$emit('drillDownName', { regioncode: regionCode, regionname: regionName })
                    self.$store.dispatch('changefeature', results.feature)
                  }
                })
            }
          }
          // 如果飞线图层已经实例化，则在地图刷新后置空
          if (self.odLayer) {
            self.refreshMapData().then(function (e) {
              if (self.odLayer) {
                self.isODLayer = false
                self.odLayer = null
              }
            })
          }
        }, function (error) {
          self.mapViewLoaded = false
        })
      }
    },
    // 根据regionlevel,regioncode等变化刷新地图
    async refreshMapData () {
      const [Point, SpatialReference] = await loadEsriModule([
        'esri/geometry/Point',
        'esri/geometry/SpatialReference'
      ])
      // 判断是否偏移
      let isOffSet = this.screenWidth > 3200
      let params = JSON.parse(this.paramsCondition)
      let sr = new SpatialReference({
        wkt: env.getInitialExtent().wkt
      })
      let regionLevel = parseInt(params['regionlevel'])
      let regioncode = params['regioncode']
      let regionname = params['regionname']
      let month = this.$store.getters.curmonth
      // 如果是东西城区，中心点不向右移动2000米
      let isEastOrWest = regioncode.slice(0, 6) == '110101' || regioncode.slice(0, 6) == '110102'
      if (regionLevel < 4) {
        if (regioncode.length == 9) {
          regioncode += '000'
        }
        let key = isOffSet ? ('offset' + (regionLevel - 1)) : (regionLevel - 1)
        let offSetX1 = isOffSet ? 2000 : 0
        let offSetX2 = isOffSet ? 8000 : 2000
        let center = regionCenters[key][regioncode]
        if (center) {
          let viewpoint = new Point({
            x: regionLevel == 3 ? isEastOrWest ? (center[0] + offSetX1) : (center[0] + offSetX2) : center[0],
            y: center[1],
            spatialReference: sr
          })
          this.mapData.feature = viewpoint
        }
      } else {
        this.mapData.feature = this.curfeature
      }

      this.mapData.regionlevel = regionLevel
      this.mapData.regioncode = regioncode
      this.mapData.regionname = regionname
      this.mapData.renderData = this.$store.getters.curmapdata ? this.$store.getters.curmapdata : []
      let mainCenter = isOffSet ? env.getInitialExtent().center2 : env.getInitialExtent().center
      this.mapData.center = new Point({
        x: mainCenter[0],
        y: mainCenter[1],
        spatialReference: sr
      })
      this.defaultCenter = this.mapData.center
      if (this.mapID == 'vector') {
        // 切换图例显示内容
        if (regionLevel >= 3) {
          this.legendData[0].visible = true
          this.legendData[0].items = this.legendDataDict['spotsdetail'][0]
          this.legendData[0].items[0].label = month != '13' ? this.curYear + '年' + month + '月' + '拆违图斑' : this.curYear + '年全年拆违图斑'
          this.legendData[0].items[0].alias = month != '13' ? this.curYear + '年' + month + '月' + '拆违图斑' : this.curYear + '年全年拆违图斑'
        } else {
          this.switchLegend(this.$route.path, this.$store.getters.curindex)
        }
      }
      // 如果数据中存在fromName属性，说明是要绘制od图层，否则就是一般的气泡图
      if (this.mapData.renderData.length > 0 && this.mapData.renderData[0]['fromName']) {
        this.createODLayer(this.mapData.renderData)
      } else {
        this.mapSwitch(this.mapData)
      }
      return 'mapRefreshDone'
    },
    // 图斑详情页图斑点击事件
    async initMapViewClick () {
      var self = this
      const [IdentifyTask, IdentifyParameters] = await loadEsriModule(['esri/tasks/IdentifyTask', 'esri/tasks/support/IdentifyParameters'])
      this.mapView.when(function (view) {
        view.on('click', function (event) {
          var identifyTask, params
          identifyTask = new IdentifyTask(env.getOtherMapServer().chaiwei[self.curYear.toString()])
          params = new IdentifyParameters()
          params.tolerance = 3
          params.layerIds = [0]
          params.layerOption = 'visible'
          params.width = self.mapView.width
          params.height = self.mapView.height
          params.returnGeometry = true
          params.geometry = event.mapPoint
          params.mapExtent = self.mapView.extent
          identifyTask
            .execute(params)
            .then(function (response) {
              view.graphics.removeAll()
              // console.log(response.results[0].feature.attributes)
              let year = self.$store.getters.curyear
              let attributes = response.results[0].feature.attributes
              let baseInfodata = MapUtils.displayFieldsInfo(year, attributes)
              bus.$emit('getspotsbaseinfo', baseInfodata)
              let graphic = response.results[0].feature
              self.highlightFeature(self.$store.getters.leftMapView, graphic)
              self.highlightFeature(self.$store.getters.rightMapView, graphic)
              self.$store.dispatch('changefeature', [graphic])
            })
        })
      }).then(function () {
        self.mapViewLoaded = true
      })
    }
  },
  mounted: function () {
    // this.screenWidth = document.body.clientWidth
    // this.screenHeight = document.body.clientHeight
    // window.onresize = () => {
    //   return (() => {
    //     this.screenWidth = document.body.clientWidth
    //     this.screenHeight = document.body.clientHeight
    //     this.refreshMapData()
    //     let regionLevel = parseInt(this.$store.getters.curRegionLevel)
    //     MapUtils.createGraphicsLayer(this.mapView, regionLevel, this.$store.getters.curRegionCode, this.curMapData, this.curColor)
    //   })()
    // }
    let isOffSet = this.screenWidth > 3200
    this.initMapView(isOffSet)
  }
}
</script>

<style lang="stylus">

    @import url('../assets/styles/iconfont/iconfont.css');

    // .workspace
        // position relative

    /*.workspace,*/
    .map-container
        height 100%
        outline 0
        // background: #fff
        // opacity: 0.1
    .esri-ui .esri-popup  {
      // width: 260px;
      // height: 150px
       width: auto;
      height: auto;
      border-radius: 2px;
      box-shadow: 3px 3px 3px rgba(0,0,0,.5);
    }
    .esri-view-width-xlarge .esri-popup__main-container {
        width: auto !important;
        outline: none !important;
        background: black!important
        opacity: 0.8;
        border-radius: 2px;
    }
    .esri-feature__main-container {
      background: black!important
    }
    .esri-popup__content {
      margin: 0px 7px 12px
      overflow: visible!important;
      overflow-x: visible!important;
    }
    .esri-widget__table {
        color: #fff;
        border: none;
        border-collapse: collapse;
        width: 100%;
    }
    .esri-widget__table tr th {
        border-right: none;
        color: white;
    }
    .esri-widget__table table th {
        font-weight: none;
        border-bottom-width: none;
        border-bottom-color: none;
    }
    .esri-popup__header{
      border-bottom: 1px solid #ddd;
    }
    .esri-popup__header-title {
        font-size: 16px;
        padding: 11px 15px;
        margin: 0 auto 0 0;
        display: block;
        white-space: pre-wrap;
        word-break: break-all;
        word-wrap: break-word;
        color: #fff;
        margin-left: 10px;
        font-weight:bold;
    }
    .esri-popup__inline-actions-container {
        display: contents;
        justify-content: flex-end;
        width: 39%;
        align-items: center;
        overflow: visible;
    }
    .esri-popup__inline-actions-container .esri-popup__action {
        /* flex: 0 0; */
        /* flex-basis: calc(100% - 15px); */
        /* padding-right: 0; */
        /* padding-left: 0; */
        // margin-right: 71px !important;
        // margin-left: 27px !important;
        color: #fff
    }
    .esri-widget {
      color: #fff;
      font-family: "sans-serif";
    }
   .esri-popup__action-text {
     text-decoration: underline
   }
    .esri-popup__pointer-direction {
        background-color: black;
        // opacity: 0.6;
        content: "";
        position: absolute;
        width: 20px;
        height: 20px;
    }
    .esri-popup--aligned-bottom-center .esri-popup__pointer-direction{
      bottom: -12px;
    }
    .esri-popup__navigation {
      left: 176px;
      z-index: 1;
      left: 50%;
    }
    .esri-popup__button--dock {
      display: none;
    }
    .esri-feature__content-element {
        padding: 0 0px 0px;
    }
    .esri-feature ul {
        margin-bottom: 1rem;
        padding: 8px 0px 0px 2rem;
    }
    .esri-popup__button {
      color: #fff
    }
    .esri-popup__button:hover{
      color:#fdc610;
    }
    .esri-popup__feature-menu-button:hover,
    .esri-popup__feature-menu-button:focus{
      box-shadow:none;
    }
    .esri-popup__feature-menu-button{
      background-color:transparent;
    }
    // .esri-popup__button .esri-popup__feature-menu-button {
    //   color: #000!important;
    // }
    // .esri-popup__button .esri-popup__pagination-previous,
    // .esri-popup__button .esri-popup__pagination-next{
    //   color: #fff
    // }
    .esri-popup__inline-actions-container .esri-popup__action {
      outline: none
    }
    .esri-popup--aligned-top-center .esri-popup__pointer {
        top: 96%;
        opacity: 0.6;
    }
    // .esri-popup__inline-actions-container {
    //     width: 15% !important;
    // }

    .toolbar
        position: absolute;
        bottom: 10px;
        // left: 286px;
        left:20px;
        z-index: 1;
        border: 2px solid rgba(0, 0, 0, 0.2);
        // box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.4) !important;
        box-shadow: 0 10px 20px 0 rgba(0, 0, 0, 0.8);
        border-radius: 4px;

        .toolbar-item
          .toolbar-item-pane
            width 184px
            margin-left 33px
            margin-top -98px
            background #1e1e1e
            border-radius 3px
        .toolbar-item
          .layer-opacity
            width 200px
          .layer-opacity
            & > span
              margin-left -89px
        .el-switch
          margin-left 0px
          font-size 12px
        .el-switch__label
          color #fff
        .el-slider
            margin-left: 5px;
            width: 165px;
        .toolbar-item
            text-align: center;
            border: 1px solid rgba(0, 0, 0, .2);
            background: rgb(30, 30, 30);
            color: #aaa;
            width: 30px;
            height: 30px;
            line-height: 30px !important;
            cursor: pointer;
            position relative

            &:hover
                color: #eee !important;

            & > .toolbar-item-open
                position absolute

        .toolbar-item:first-child
            border-top-left-radius: 2px;
            border-top-right-radius: 2px;

        .toolbar-item:last-child
            border-bottom-left-radius: 2px;
            border-bottom-right-radius: 2px;
    .toolbar-item
        &:hover .toolbar-item-open
            display block

        .toolbar-item-open
            display none
            bottom -4px
            left 50px
            width 200px
            background #222
            & > label
                float left

            & > label,
            .el-checkbox.is-bordered + .el-checkbox.is-bordered
                color #fff
                margin 0
                padding 5px 20px
        // .layer-opacity
        //     width: 130px
            // margin-left: 20px

    //     &:hover
    //         background #000

    // & > label.is-checked
    //     background #000

    .overlay-show
        position absolute
        top 0
        left 0
        z-index 1

// 非图斑页图例
.rmap .map-legend-wrapper {
    position: absolute;
    z-index: 1;
    padding: 14px;
    right: 35%;
    bottom: 10px;
    background: rgba(30, 30, 30, 0.95);
    box-shadow: 0 10px 20px 0 rgba(0, 0, 0, 0.8);
}
//图斑页图例
.map-time .map-legend-wrapper {
  right 20px
  position: absolute;
  z-index: 1;
  padding: 14px;
  bottom: 10px;
  background: rgba(30, 30, 30, 0.95);
  box-shadow: 0 10px 20px 0 rgba(0, 0, 0, 0.8);
}

  // 滚动条
// .decorate-list
//   overflow-y auto
//   max-height 200px
// .el-scrollbar__wrap
//   overflow-x: hidden;
//   overflow-y hidden;

.esri-view .esri-view-surface
  outline none!important
.esri-popup__main-container
  background rgba(0,0,0,.7)!important
</style>
